﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;


namespace SP2010_Starter.ControlTemplates.SP2010_Starter
{
    public partial class MegaDropDown : UserControl
    {
        SPSite siteCollection;
        SPWeb site;
       
        SPListCollection lists;
        SPList menuList;
        LiteralControl output;

        protected void Page_Load(object sender, EventArgs e)
        {       

        }

        protected override void CreateChildControls()
        {
           //TODO: Add error handling
            //TODO: RunWIthElevatedPrivileges
            
            //Get listitems to render
            siteCollection = SPContext.Current.Site;
            site = siteCollection.RootWeb;         

            // Get a ListCollection from the current site
            lists = site.Lists;
            menuList = lists["Mega Drop Down Menu"];
           
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            if (menuList != null)
            {
                if (menuList.Items.Count > 0)
                {                  
                    
                    //Begin menu
                    writer.WriteLine("<ul id=\"menu\">");

                    // Create a SPQuery Object
                    SPQuery curQry = new SPQuery();
                                   
                    //Write the query order the list in the order defined in the list
                    //curQry.Query = "<Where><Eq><FieldRef Name='Order' /><Value Type='Number'>" + i + "</Value></Eq></Where>";
                    curQry.Query = "<OrderBy><FieldRef Name='ItemOrder' Ascending='True' /></OrderBy>";
                    curQry.RowLimit = 100;

                    //Get the Items using Query
                    SPListItemCollection curItems = menuList.GetItems(curQry);

                    //Render Items                    
                    foreach (SPListItem item in curItems)
                    {                                               
                        writer.WriteLine(item["HTML"]);                       
                    }

                    //End menu
                    writer.WriteLine("</ul>");
                }
            }
        }
    }
}
